package com.twu.biblioteca.controller;

import com.twu.biblioteca.BibliotecaApp;
import com.twu.biblioteca.DAO.UserDAO;
import com.twu.biblioteca.model.User;

import java.util.Scanner;

/**
 * Created by akutschm on 06/05/2014.
 */
public class LoginController extends AbstractController implements Controller {

    String login = null;
    String password = null;

    public LoginController(Scanner reader, BibliotecaApp app) {
        super(reader, app);

        println("Enter your username and password to login (try u:123-4567 p:1234)\n");
        print("Username: ");
        handleUserInput();
    }

    @Override
    public void doHandleUserInput(String input) {
        switch (input) {
            case "Quit":
                handleUserInput = false;
                println("Have a nice day!");
                break;
            default:
                if (login == null) {
                    login = input;
                    print("Password: ");
                } else {
                    password = input;
                    validate();
                }
        }
    }

    protected void validate() {
        User user = checkCredentials(login, password);
        if (user == null) {
            println("\nWrong login or password. Please try again. (try u:123-4567 p:1234)\n");
            login = null;
            password = null;
            print("Username: ");
        } else {
            app().setUser(user);
            println("\nWelcome, " + user.getName());
            goTo(Place.MAIN_MENU);
        }
    }

    User checkCredentials(String login, String password) {
        UserDAO dao = app().getUserDAO();
        return dao.find(login, password);
    }
}
